<?php


namespace app\admin\controller;

use app\common\model\GiftModel;
use app\common\model\LiveStoreModel;
use app\common\model\LiveStoreOrderModel;
use app\common\model\PropsNewModel;
use app\common\model\UserAddressModel;
use think\db\Query;
use think\facade\Request;
use think\Validate;

class LiveStoreController extends BaseController
{
    /**
     * 商品列表
     * @return mixed
     */
    public function index()
    {
        return $this->fetch();
    }

    /**
     * 添加商品
     * @return mixed
     */
    public function add()
    {
        if (Request::isPost()) {
            $all_param = Request::param();

            $validate = new Validate([
                'type'         => 'require|in:1,2',
                'title'        => 'length:2,100',
                'thumb'        => 'require|url',
                'limit'        => 'require|number',
                'vip_discount' => 'require|in:1,2',
                'diamond'      => 'require',
                'gold'         => 'require',
                'sort'         => 'require|number|egt:1',
                'content'      => 'require|length:2,200',

            ], [
                "type"         => "请选择商品类型",
                "title"        => "商品名称在2-100个字符",
                "thumb"        => "请上传商品图片",
                'limit'        => '请正确输入商品期限',
                'vip_discount' => '请正确选择贵族折扣',
                'diamond'      => '请正确输入宝石价格',
                'gold'         => '请正确输入钻石价格',
                'sort'         => '请正确输入排序',
                'content'      => '商品介绍在2-200个字符',
            ]);

            if (!$validate->check($all_param)) {
                return self::bulidFail($validate->getError());
            }

            if ($all_param['diamond'] <= 0 && $all_param['gold'] <= 0) {
                return self::bulidFail('宝石和钻石价格不能同时为0');
            }

            $store_model             = new LiveStoreModel($all_param);
            $store_model->created_at = time();
            $store_model->admin_id   = $this->admin_id;
            $store_model->diamond    = bcmul($store_model->diamond, 100);
            $store_model->gold       = bcmul($store_model->gold, 100);
            $store_model->gift_id    = 0;
            $store_model->props_id   = 0;

            // 礼物还是道具
            $gift_props = explode('_', $store_model->gift_props);
            if (isset($gift_props[0]) && isset($gift_props[1])) {
                switch ($gift_props[0]) {
                    case 'gift':
                        $store_model->gift_id = intval($gift_props[1]);
                        $store_model->title   = GiftModel::where('id', $store_model->gift_id)->value('title');
                        break;

                    case 'props':
                        $store_model->props_id = intval($gift_props[1]);
                        $store_model->title    = PropsNewModel::where('id', $store_model->props_id)->value('name');
                        break;
                }
            }

            // 如果是虚拟物品则验证是否正确选择
            if ($store_model->type == 1 && $store_model->gift_id < 1 && $store_model->props_id < 1) {
                return self::bulidFail('请正确选择虚拟物品');
            }

            if ($store_model->save()) {
                // 记录日志
                $log_content = "添加商品，ID：{$store_model->id}，商品名称：{$store_model->title}";
                parent::addAdminLog($log_content);

                return self::bulidSuccess();
            }
            return self::bulidFail();
        }

        $gift_list  = GiftModel::where(['type' => 2, 'status' => 1])->select();
        $props_list = PropsNewModel::select();

        return $this->assign([
            'gift_list'  => $gift_list,
            'props_list' => $props_list
        ])->fetch();
    }

    /**
     * 编辑商品
     * @return mixed
     */
    public function edit()
    {
        $id         = Request::param('id');
        $live_store = LiveStoreModel::get($id);

        if (!$live_store) {
            return self::bulidFail('商品信息不存在');
        }

        if (Request::isPost()) {
            $all_param = Request::param();

            $validate = new Validate([
                'type'         => 'require|in:1,2',
                'title'        => 'length:2,100',
                'thumb'        => 'require|url',
                'limit'        => 'require|number',
                'vip_discount' => 'require|in:1,2',
                'diamond'      => 'require',
                'gold'         => 'require',
                'sort'         => 'require|number|egt:1',
                'content'      => 'require|length:2,200',

            ], [
                "type"         => "请选择商品类型",
                "title"        => "商品名称在2-100个字符",
                "thumb"        => "请上传商品图片",
                'limit'        => '请正确输入商品期限',
                'vip_discount' => '请正确选择贵族折扣',
                'diamond'      => '请正确输入宝石价格',
                'gold'         => '请正确输入钻石价格',
                'sort'         => '请正确输入排序',
                'content'      => '商品介绍在2-200个字符',
            ]);

            if (!$validate->check($all_param)) {
                return self::bulidFail($validate->getError());
            }

            if ($all_param['diamond'] <= 0 && $all_param['gold'] <= 0) {
                return self::bulidFail('宝石和钻石价格不能同时为0');
            }

            $all_param['admin_id'] = $this->admin_id;
            $all_param['diamond']  = bcmul($all_param['diamond'], 100);
            $all_param['gold']     = bcmul($all_param['gold'], 100);
            $all_param['gift_id']  = 0;
            $all_param['props_id'] = 0;

            // 礼物还是道具
            $gift_props = explode('_', $all_param['gift_props']);
            if (isset($gift_props[0]) && isset($gift_props[1])) {
                switch ($gift_props[0]) {
                    case 'gift':
                        $all_param['gift_id'] = intval($gift_props[1]);
                        $all_param['title']   = GiftModel::where('id', $all_param['gift_id'])->value('title');
                        break;

                    case 'props':
                        $all_param['props_id'] = intval($gift_props[1]);
                        $all_param['title']    = PropsNewModel::where('id', $all_param['props_id'])->value('name');
                        break;
                }
            }

            // 如果是虚拟物品则验证是否正确选择
            if ($all_param['type'] == 1 && $all_param['gift_id'] < 1 && $all_param['props_id'] < 1) {
                return self::bulidFail('请正确选择虚拟物品');
            }

            if ($live_store->save($all_param)) {
                // 记录日志
                $log_content = "修改商品，ID：{$live_store->id}，商品名称：{$live_store->title}";
                parent::addAdminLog($log_content);

                return self::bulidSuccess();
            }
            return self::bulidFail();
        }


        $live_store->gold    = bcdiv($live_store->gold, '100', 2);
        $live_store->diamond = bcdiv($live_store->diamond, '100', 2);

        $gift_list  = GiftModel::where(['type' => 2, 'status' => 1])->select();
        $props_list = PropsNewModel::select();

        return $this->assign([
            'live_store' => $live_store,
            'gift_list'  => $gift_list,
            'props_list' => $props_list
        ])->fetch();
    }

    /**
     * 商品列表页数据
     * @return \think\response\Json
     */
    public function getlist()
    {
        $title      = Request::get('title');
        $type       = Request::get('type');
        $price_type = Request::get('price_type');
        $status     = Request::get('status');
        $start_time = Request::get("start_time", '0', 'strtotime');
        $end_time   = Request::param("end_time", '0', 'strtotime');
        // 分页
        $page  = Request::param("page");
        $limit = Request::param("limit");

        $where = [];
        if ($type) {
            $where[] = ['type', '=', $type];
        }

        if (is_numeric($status)) {
            $where[] = ['status', '=', $status];
        }

        if ($price_type > 0) {
            if ($price_type == 1) {
                $where[] = ['gold', '>', 0];
            } else {
                $where[] = ['diamond', '>', 0];
            }
        }

        if ($start_time) {
            $where[] = ['created_at', '>=', $start_time];
        }
        if ($end_time) {
            $where[] = ['created_at', '<=', $end_time];
        }

        if (mb_strlen($title, 'UTF-8') > 0) {
            $where[] = ['title', 'like', "%$title%"];
        }

        $count = LiveStoreModel::where($where)->count("id");

        if ($count > 0) {
            $list = LiveStoreModel::with(['gift', 'props', 'admin' => function ($query) {
                $query->field('id,name');
            }])
                ->where($where)
                ->order('id desc')
                ->page($page, $limit)
                ->select()->each(function ($query) {
                    if ($query->created_at) {
                        $query->created_at = date('Y-m-d H:i:s', $query->created_at);
                    }
                    if ($query->gold) {
                        $query->gold = bcdiv($query->gold, '100', 2);
                    }

                    if ($query->diamond) {
                        $query->diamond = bcdiv($query->diamond, '100', 2);
                    }
                });

            return json(["code" => 0, "msg" => "", "data" => $list, "count" => $count]);
        }

        return self::bulidFail('暂无数据');
    }

    /**
     * 上下架商品
     * @return \think\response\Json
     */
    public function set_status()
    {
        $status     = Request::param("status");
        $live_store = LiveStoreModel::get(Request::param("id"));
        if (!$live_store) {
            return self::bulidFail("商品信息不存在");
        }

        $live_store->status = $status;

        if ($live_store->save()) {
            // 记录日志
            $log_content = ($status == 1 ? '上架' : '下架') . "商品，ID：{$live_store->id}，标题：{$live_store->title}";
            parent::addAdminLog($log_content);

            return self::bulidSuccess();
        }
        return self::bulidFail();
    }

    /**
     * 订单页面
     * @return mixed
     */
    public function order()
    {
        if ($this->request->isAjax()) {
            $model = LiveStoreOrderModel::field('*');
            if ($title = trim($this->get('title', ''))) {
                $model = $model->whereLike('title', $title . '%');
            }

            if (in_array($type = $this->get('type', ''), ['1', '2'])) {
                $model = $model->where('type', $type);
            }

            if (in_array($price_type = $this->get('price_type', ''), ['1', '2'])) {
                if ($price_type == 1) {
                    $model = $model->where('gold', 0);
                } else {
                    $model = $model->where('diamond', 0);
                }
            }

            if (($start_time = strtotime($this->get('start_time', ''))) && ($end_time = strtotime($this->get('end_time', '')))) {
                $model = $model->whereBetween('created_at', [$start_time, $end_time + 86399]);
            } elseif ($start_time) {
                $model = $model->whereBetween('created_at', [$start_time, time()]);
            }

            return json([
                'count' => $model->count('id'),
                'list'  => $model->with([
                    'user_address' => function (Query $query) {
                        $query->field('id,name,address,mobile');
                    }
                ])
                    ->order('id', 'desc')
                    ->page($this->get('page', 1), $this->get('limit', 20))
                    ->select()->each(function ($query) {
                        if ($query->created_at) {
                            $query->created_at = date('Y-m-d H:i:s', $query->created_at);
                        }
                        if ($query->ship_time) {
                            $query->ship_time = date('Y-m-d H:i:s', $query->ship_time);
                        }

                        if ($query->gold) {
                            $query->gold = bcdiv($query->gold, '100', 2);
                        }

                        if ($query->diamond) {
                            $query->diamond = bcdiv($query->diamond, '100', 2);
                        }
                    })
                    ->toArray(),
                'code'  => 0,
            ]);
        }

        return $this->fetch();
    }

    public function order_edit()
    {
        if (!ctype_digit($id = $this->get('id', ''))) {
            return static::bulidFail('订单ID错误');
        }

        if (!$model = LiveStoreOrderModel::where('id', $id)->find()) {
            return static::bulidFail('非法订单');
        }

        if ($this->request->isAjax()) {
            if (!$name = trim($this->post('name', ''))) {
                return static::bulidFail('收货人姓名不能为空');
            }

            if (!$mobile = trim($this->post('mobile', ''))) {
                return static::bulidFail('收货人手机不能为空');
            }

            if (!ctype_digit($mobile)) {
                return static::bulidFail('收货人手机错误');
            }

            if (!$address = trim($this->post('address', ''))) {
                return static::bulidFail('收货人地址不能为空');
            }

            if (!$express_no = trim($this->post('express_no', ''))) {
                return static::bulidFail('运单号不能为空');
            }

            if (!$userInfo = UserAddressModel::field('id,name,mobile,address')->where('id', $model->user_address_id)->where('uid', $model->uid)->find()) {
                $userInfo = new UserAddressModel();
            }

            $userInfo->name    = $name;
            $userInfo->mobile  = $mobile;
            $userInfo->address = $address;
            $userInfo->uid     = $model->uid;
            if (!$userInfo->save()) {
                return static::bulidFail('编辑收货人信息失败');
            }

            $model->user_address_id = $userInfo->id;
            $model->operator        = $this->admin_name;
            $model->status          = 1;
            $model->express_no      = $express_no;
            $model->ship_time       = time();

            if (!$model->save()) {
                return static::bulidFail();
            }

            $this->addAdminLog('为用户:' . $model->uid . ' 进行了发货', $model->uid);

            return static::bulidSuccess();
        }

        $userInfo          = new \stdClass();
        $userInfo->name    = '';
        $userInfo->mobile  = '';
        $userInfo->address = '';

        if ($model->user_address_id) {
            if ($userInfoTmp = UserAddressModel::field('name,mobile,address')->where('id', $model->user_address_id)->where('uid', $model->uid)->find()) {
                $userInfo = $userInfoTmp;
            }
        }

        $model->user_name = $userInfo->name;
        $model->mobile    = $userInfo->mobile;
        $model->address   = $userInfo->address;

        return $this->assign(['model' => $model])->fetch();
    }
}